import React, { Component } from "react";
import { Suspense } from "react-router-dom";

class ErrorBoundary extends Component {
  // hasError:是否有错
  state = {
    hasError: false,
  };

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error) {
    // 可以做一些错误的打印
    console.log(error);
  }

  handleRetry = () => {
    this.setState({ hasError: false });
  };

  render() {
    const { hasError } = this.state;
    const { children } = this.props;
    if (hasError) {
      return (
        <div>
          <span>出错了</span>
          <button onClick={this.handleRetry}>请重试</button>
        </div>
      );
    }
    return children;
  }
}

export const withRetry = loadAction => props => (
    <ErrorBoundary>
      {() => {
        const Component = React.lazy(loadAction);
        return (
          <Suspense>
            <Component {...props} />
          </Suspense>
        );
      }}
    </ErrorBoundary>
  );
